package wallet

import (
	"ChainCodeProject/tools"
	"bytes"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"errors"
)

const VERSION = 0x00 //版本号
/**
 * @author: 清秋
 * @email: 15770670622
 * @datetime: 9:20 2022/5/25
 * @Description:
 */

//生成公钥和私钥
func NewPubKeys(curve elliptic.Curve) (*ecdsa.PrivateKey, *ecdsa.PublicKey, error) {

	//生成私钥
	privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
	if err != nil {
		return nil, nil, err
	}
	//生成公钥
	publicKey := privateKey.PublicKey

	return privateKey, &publicKey, nil
}

/**
//用来生成地址
func GenerateAddr() (string, error) {
	//生成一个p256的一个曲线
	curve := elliptic.P256()

	_, pub, err := NewPubKeys(curve)
	if err != nil {
		return "", err
	}

	//进行转换 序列化把公钥转为字节切片类型[]bytes
	pub_bytes := elliptic.Marshal(curve, pub.X, pub.Y)

	//对公钥进行sha256计算
	pub_sha256 := tools.GetHash(pub_bytes)

	//对pub_sha256进行ripemd160计算 160位，20个字节
	pubhash := tools.Ripemd160(pub_sha256)

	//将版本号和pubhash拼接
	ver_pubhash := append([]byte{VERSION}, pubhash...)

	//进行sha256运算
	first_hash := tools.GetHash(ver_pubhash)
	second_hash := tools.GetHash(first_hash)
	check := second_hash[:4]

	//将ver_pubhash和check进行拼接
	ver_pubhash_check := append(ver_pubhash, check...)

	//将ver_pubhash_check进行base58转换
	addr := tools.Encode(ver_pubhash_check)
	return addr, nil
}

*/

//判断地址是否合法
func checkAddr(addr string) bool {
	//1,进行解密
	ver_pubhash_check := tools.Decode(addr)

	//2.对ver_pubhash_check进行截取
	check := ver_pubhash_check[len(ver_pubhash_check)-4:]
	ver_pubhash := ver_pubhash_check[:len(ver_pubhash_check)-4]

	//3.对ver_pubhash进行双sha256计算
	first_hash := tools.GetHash(ver_pubhash)
	second_hash := tools.GetHash(first_hash)

	//4.对second_hash进行截取前四位
	newCheck := second_hash[:4]

	//5.进行比较
	return bytes.Compare(check, newCheck) == 0

}

//获取对应地址的公钥hash值
func GetPubHash(addr string)([]byte,error){
	istrue := checkAddr(addr)
	if !istrue {
		return nil,errors.New("地址不合法！")
	}
	ver_pubhash_check := tools.Decode(addr)
	ver_pubhash := ver_pubhash_check[:len(ver_pubhash_check)-4]
	pubhash := ver_pubhash[1:]
	return pubhash,nil

}
